package org.devocean.groupbuying.dao.impl;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.devocean.groupbuying.dao.PurchaseDAO;
import org.devocean.groupbuying.domain.Purchase;
import org.springframework.stereotype.Repository;

@Repository
public class PurchaseDAOImpl implements PurchaseDAO {

	@PersistenceContext
	private EntityManager em;

	public List<Purchase> findAllPurchases() {
		return em.createQuery("select pu from Purchase pu").getResultList();
	}

	public long countPurchase() {
		return em.createQuery("select count(pu) from Purchase pu", long.class)
				.getSingleResult();
	}

	public Purchase findPurchaseById(Integer id) {
		return em.find(Purchase.class, id);
	}

	public void deletePurchase(int id) {
		final Purchase purchase = em.find(Purchase.class, id);
		if (purchase != null) {
			em.remove(purchase);
		}

	}

	public Purchase savePurchase(Purchase purchase) {
		em.persist(purchase);
		return purchase;
	}

	public Purchase updatePurchase(Purchase purchase) {
		em.merge(purchase);
		return purchase;
	}

	public List<Purchase> findPurchasesByCustomer(Integer customerID) {
		return em
				.createQuery("SELECT pu FROM Purchase pu WHERE pu.customer.customerID =:cid", Purchase.class)
				.setParameter("cid", customerID).getResultList();

	
	}

	public List<Purchase> findPurchasesByCustomer(Integer customerID,
			String lang) {
		
		return  em
				.createQuery("SELECT serial FROM SerialKey serial " +
						"INNER JOIN FETCH serial.item item " +
						"INNER JOIN FETCH item.purchase pu " +
						" WHERE pu.customer.customerID =:cid", Purchase.class)
				.setParameter("cid", customerID).getResultList();
	}

	public Long countPurchaseByCustomer(Integer customerID) {
		
		return em.createQuery("select COUNT(sek) from Purchase pu " +
								"INNER JOIN pu.items puitem INNER JOIN puitem.serialKeys sek ",Long.class).getSingleResult();
	}

}
